package com.ruoyi.web.controller.mes;

import com.alibaba.excel.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.filedown;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.web.controller.mes.report.PersionReportController;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.domain.mes.*;
import com.ruoyi.web.domain.vo.*;
import com.ruoyi.web.mapper.MesConfigMapper;
import com.ruoyi.web.mapper.MesOrderMapper;
import com.ruoyi.web.mapper.MesPaperMapper;
import com.ruoyi.web.service.*;
import com.ruoyi.web.service.Impl.MesPaperService;
import com.ruoyi.web.vo.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.web.mapper.ProduceMapper;

@RestController
@RequestMapping("/produce")
public class ProduceController extends BaseController {
    @Autowired
    private IMesMakeVersionService mesMakeVersionService;
    @Resource
    private ProduceService produceService;
    @Resource
    private MesPaperService mesPaperService;
    @Resource
    private ProduceProductService produceProductService;
    @Resource
    private ProducePaperService producePaperService;
    @Resource
    private ProducePrintService producePrintService;
    @Resource
    private ProduceCoveringService produceCoveringService;
    @Resource
    private MesOrderProductService mesOrderProductService;
    @Resource
    private ProducePieceService producePieceService;
    @Resource
    private MesConfigMapper configMapper;
    @Resource
    private ProduceMapper produceMapper;
    @Resource
    private MesProducePieceMachineService mesProducePieceMachineService;
    @Resource
    private MesOrderMapper mesOrderMapper;
    @Resource
    private MesPaperMapper paperMapper;
    @Resource
    private MesMachineService mesMachineService;
    @Resource
    private MesRotateService mesRotateService;
    @Resource
    private IMesReportWork MesReportWork;
    @Resource
    private OtherReportDetailService reportDetailService;
    @Resource
    private ReportWorkService reportWorkService;
    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @GetMapping(value = "/selectNWProducePrint")
    public TableDataInfo selectNWProducePrint(Produce produce) {
        startPage();
        List<NWProducePrint> NWProducePrintList = produceMapper.selectNWProducePrint(produce);
        return getDataTable(NWProducePrintList);
    }

    @GetMapping(value = "/selectFMDetailList")
    public TableDataInfo selectFMDetailList(Produce produce) {
        startPage();
        List<Produce> produces = produceMapper.getListFMDetail(produce);
        return getDataTable(produces);
    }

    @ApiOperation("导出封面生产单明细")
    @Log(title = "导出封面生产单明细", businessType = BusinessType.EXPORT)
    @PostMapping(value = "/exportFMDetailList")
    public void exportFMDetailList(HttpServletResponse response, @RequestBody Produce produce) throws IOException {

        List<Produce> list = produceMapper.getListFMDetail(produce);
        //获取模版
        InputStream inputStream = PersionReportController.class.getClassLoader().getResourceAsStream("temlates/coverProduceDetail.xlsx");
        filedown filedownexcel = new filedown();
        String name = "封面生产单明细查询";
        Map<String, Object> map = MapUtils.newHashMap();
        //map.put("date",date);
        //引入方法传入集合、response,模版的输入流
        filedownexcel.filedownexcels(list, response, name, inputStream, map);
    }

    @PostMapping(value = "/list")
    public TableDataInfo list(@RequestBody Map<String, String> params) {
        Produce produce = new Produce();

        String orderNo = params.get("orderNo");//订单编号
        String produceNo = params.get("produceNo");//生产单编号
        String pubNo = params.get("pubNo");//出版编号
        String bookName = params.get("bookName");//书刊名称
        String bookNo = params.get("bookNo");//书刊编码
        String submitDate = params.get("submitDate");
        String type = params.get("type");
        String fmshym = params.get("fmshym");//如果是封面审核页面需要单独处理下封面的数据，如果不是不需要
        String status = params.get("status");
        String isNew = params.get("isNew");
        String newPast = params.get("newPast");
        String state = params.get("state");
        String replenish = params.get("replenish");
        String makeStatus = params.get("makeStatus");
        String startTime = params.get("startTime");//开始时间
        String endTime = params.get("endTime");//结束时间
        String customName = params.get("customName");//客户名称
        String productName = params.get("productName");//产品名称
        String workshopName = params.get("workshopName");//车间名称
        String shipmentType = params.get("shipmentType");//产品名称显示成发货品种
        if (!Objects.equals(status, "") && status != null) {
            params.put("state", "");
        }
        produce.setParams(params);
        startPage(params);
        List<Produce> produces = new ArrayList<>();
        if (StringUtils.isNotEmpty((fmshym)) && StringUtils.isNotEmpty(type) && type.equals("1")) {
            produces = produceMapper.getListFM(produce);
        } else {
            produces = produceMapper.getList(produce);
            if(produces.size() > 0){
                int countTotal = 0;
                for (Produce produce1 : produces) {
                    if(StringUtils.isNotEmpty(produce1.getBookNo()) && StringUtils.isNotEmpty(produce1.getProduceCount())){
                        countTotal = countTotal + Integer.parseInt(produce1.getProduceCount() ); //封面获取印刷管理中的印数
                    }
                }
                produces.get(0).setCountTotal(countTotal);
            }
        }
        return getDataTable(produces);

//        List<Integer> statusList = new ArrayList<>();
//        // 向列表中添加状态
//        statusList.add(0);
//        statusList.add(-2);
    }


    @ApiOperation("封面生产单")
    @Log(title = "封面生产单", businessType = BusinessType.EXPORT)
    @PostMapping(value = "/listexport")
    public void listexport(HttpServletResponse response,@RequestParam Map<String, String> params) {
        System.out.println("-------------------vvvvvvvvvvvvvv");
        Produce produce = new Produce();
        String orderNo = params.get("orderNo");//订单编号
        String produceNo = params.get("produceNo");//生产单编号
        String pubNo = params.get("pubNo");//出版编号
        String bookName = params.get("bookName");//书刊名称
        String bookNo = params.get("bookNo");//书刊编码
        String submitDate = params.get("submitDate");
        String type = params.get("type");
        String fmshym = params.get("fmshym");//如果是封面审核页面需要单独处理下封面的数据，如果不是不需要
        String status = params.get("status");
        String isNew = params.get("isNew");
        String newPast = params.get("newPast");
        String state = params.get("state");
        String replenish = params.get("replenish");
        String makeStatus = params.get("makeStatus");
        String startTime = params.get("startTime");//开始时间
        String endTime = params.get("endTime");//结束时间
        String customName = params.get("customName");//客户名称
        String productName = params.get("productName");//产品名称
        String workshopName = params.get("workshopName");//车间名称
        String shipmentType = params.get("shipmentType");//产品名称显示成发货品种
        if (!Objects.equals(status, "") && status != null) {
            params.put("state", "");
        }
        produce.setParams(params);
//        startPage(params);
        List<Produce> produces = new ArrayList<>();
        if (StringUtils.isNotEmpty((fmshym)) && StringUtils.isNotEmpty(type) && type.equals("1")) {
            produces = produceMapper.getListFM(produce);
        } else {
            produces = produceMapper.getList(produce);
            if(produces.size() > 0){
                int countTotal = 0;
                for (Produce produce1 : produces) {
                    if(StringUtils.isNotEmpty(produce1.getBookNo()) && StringUtils.isNotEmpty(produce1.getProduceCount())){
                        countTotal = countTotal + Integer.parseInt(produce1.getProduceCount() ); //封面获取印刷管理中的印数
                    }
                }
                produces.get(0).setCountTotal(countTotal);
            }
        }
        ExcelUtil<Produce> util = new ExcelUtil<>(Produce.class);
        util.exportExcel(response,produces, "封面生产单查询");
    }

    @PostMapping(value = "/deliverylist")
    public TableDataInfo deliverylist(@RequestBody Map<String, String> params) {
        Produce produce = new Produce();
        produce.setParams(params);
        startPage(params);
        List<Produce> produces = new ArrayList<>();
        produces = produceMapper.getDeliveryList(produce);
        return getDataTable(produces);
    }


    //批量更改书号
    @PostMapping(value = "/updatebookNo")
    public AjaxResult updatebookNo(@RequestBody String[] ids) {
        for (String id : ids) {
            produceService.update(new UpdateWrapper<Produce>()
                    .lambda().set(Produce::getBookNo, "").eq(Produce::getProduceId, id));
        }
        return AjaxResult.success("操作成功");
    }

    //查询生产单左侧列表
    @PostMapping(value = "/GetProducelistByMachineId")
    public TableDataInfo GetProducelistByMachineId(@RequestBody Map<String, String> params) {
        startPage(params);
        String produceNo = params.get("produceNo");//生产单编号
        String machineId = params.get("machineId");
        String status = params.get("status");
        String type = params.get("type");
        Produce produce = new Produce();
        produce.setProduceNo(produceNo);
        produce.setMachineId(machineId);
        produce.setStatus(status);
        produce.setType(type);//机台类型
        //覆膜机不筛选机台
        if (Objects.equals(type, "7")) {
            produce.setMachineId(null);
        }

        List<Produce> produces = new ArrayList<>();
        if (Objects.equals(type, "4")) {//折页选择生产单时，只显示前一个工艺报工完成的的内文生产单
            produces = produceMapper.GetProducelistByMachineIdFold(produce);
        } else if (Objects.equals(type, "6") || Objects.equals(type, "5")) {//裁切选择生产单时，只显示前一个工艺报工完成的的内文生产单
            produces = produceMapper.GetProducelistByMachineIdCut(produce);
        } else if (Objects.equals(type, "7")) {//覆膜报工单，只显示印刷完成的封面生产单
            produces = produceMapper.GetProducelistByMachineIdCover(produce);
        }
        else {
            produces = produceMapper.GetProducelistByMachineId(produce);
        }
        return getDataTable(produces);
    }

    //印刷报工选择生产单左侧列表
    @PostMapping(value = "/GetReportProduce")
    public TableDataInfo GetReportProduce(@RequestBody Map<String, String> params) {
        startPage(params);
        String produceNo = params.get("produceNo");//生产单编号
        String machineId = params.get("machineId");
        String status = params.get("status");
        String type = params.get("type");
        Produce produce = new Produce();
        produce.setProduceNo(produceNo);
        produce.setMachineId(machineId);
        produce.setStatus(status);
        produce.setType(type);//机台类型
        List<Produce> produces = produceMapper.GetReportProduce(produce);
        return getDataTable(produces);
    }

    // 做版左侧选择列表1
    @PostMapping(value = "/leftListZuo")
    public TableDataInfo leftListZuo(@RequestBody Map<String, String> params) {
        startPage(params);
        String produceNo = params.get("produceNo");//生产单编号
        TableDataInfo data = getDataTable(produceService.list(new QueryWrapper<Produce>().lambda()
                .like(StringUtils.isNotEmpty(produceNo), Produce::getProduceNo, produceNo)
                .eq(Produce::getStatus, 2)
                .or().eq(Produce::getStatus, 19)
                .orderByDesc(Produce::getSubmitDate)
        ));
        return data;
    }

    //待装订生产单
    @PostMapping(value = "/bindMachineTask")
    public TableDataInfo bindMachineTask(@RequestBody Map<String, String> params) {
        String machineId = params.get("machineId");//机台id
        String produceNo = params.get("produceNo");//生产单编号
        Produce produce = new Produce();
        produce.setParams(params);
       // startPage(params);
        List<Produce> list = produceMapper.bingMachineTask(produce);
        List<Produce> tempSubmitList = produceMapper.bingMachineTaskTempSubmit(produce); //暂提的数据需要查询出来
        list.addAll(tempSubmitList);
        return getDataTable(list);
    }

    //待装订生产单对应的封面
    @PostMapping(value = "/bindFMTask")
    public TableDataInfo bindFMTask(@RequestBody Map<String, String> params) {
        String produceId = params.get("produceId");//生产单编号
        String breed = params.get("breed");//品种
        Produce produce = new Produce();
        produce.setParams(params);
        List<ScheduleVo> fmlist = produceMapper.bindFMTask(produce);
        return getDataTable(fmlist);
    }

    //查询待分配生产单
    @PostMapping(value = "/waitProduce")
    public TableDataInfo waitProduce(@RequestBody Map<String, String> params) {
        Produce produce = new Produce();
        String workshopName = params.get("workshopName");//车间名称
        String produceNo = params.get("produceNo");//生产单编号
        String type = params.get("type");//类型
        produce.setParams(params);
        startPage(params);
        List<Produce> produces = produceMapper.waitProduce(produce);
        return getDataTable(produces);
    }

    //查询装订待分配生产单
    @PostMapping(value = "/waitBinding")
    public TableDataInfo waitBinding(@RequestBody Map<String, String> params) {
        Produce produce = new Produce();
        String workshopName = params.get("workshopName");//车间名称
        String produceNo = params.get("produceNo");//生产单编号
        String type = params.get("type");//类型
        produce.setParams(params);
        startPage(params);
        List<Produce> produces = produceMapper.waitBinding(produce);
        return getDataTable(produces);
    }

    //查询装订待排产生产单
    @PostMapping(value = "/waitBindingpc")
    public TableDataInfo waitBindingpc(@RequestBody Map<String, String> params) {
        Produce produce = new Produce();
        String workshopName = params.get("workshopName");//车间名称
        String produceNo = params.get("produceNo");//生产单编号
        produce.setParams(params);
        startPage(params);
        List<Produce> produces = produceMapper.waitBindingpc(produce);
        return getDataTable(produces);
    }
    //生产单分配机台
    @PostMapping(value = "/allocationMachine")
    @Transactional
    public AjaxResult allocationMachine(@RequestBody Map<String, String> params) {
        String produceId = params.get("produceId");//生产单id
        Produce produce= produceService.getById(produceId);
        if(Objects.equals(produce.getIsFp(), "1")){
            return AjaxResult.success("分配成功");
        }else{
            produceService.AllocationMachine(produceId);
            return AjaxResult.success("分配成功");
        }
    }

    //装订分配机台
    @PostMapping(value = "/bindingMachine")
    @Transactional
    public AjaxResult bindingMachine(@RequestBody Map<String, String> params) {
        String produceId = params.get("produceId");//生产单id
        produceService.BindingMachine(produceId);
        return AjaxResult.success("分配成功");
    }

    //取板
    @PostMapping(value = "/taskMachine")
    public TableDataInfo taskMachine(@RequestBody Map<String, String> params) {
//        startPage(params);
        String machineId = params.get("machineId");//机台id
        String produceNo = params.get("produceNo");//生产单编号
//        MesMachine machine = mesMachineService.getById(machineId);

        //机台信息
        MesMachine machine = mesMachineService.getById(machineId);
        Produce produce = new Produce();
        produce.setParams(params);
        int ncount = produceMapper.machineNwCount(machineId);//机台内文已取板印刷中的数量
        int fcount = produceMapper.machineFmCount(machineId);//机台封面已取板印刷中的数量

        int num = 2;
        //卷轮机看三个
        if (machine != null && Objects.equals(machine.getModel(), "2")) {
            num = 3;
        }


        if (ncount > num && fcount > 10) {//如果内文大于2并且封面大于10
            throw new ServiceException("该机台生产单印刷中数量已达到最大数量，待印刷报工后新增。");
        }


//        List<Produce> produces = produceMapper.taskMachine(machineId);
        //内文待取板的
        List<Produce> nwproduces = produceMapper.nwtakeMachine(produce);
        //封面待取板的(已分配就能取板)
        List<Produce> fmproduces = new ArrayList<>();

         //查询已取板但未报工的最小时间
        //20240809 修改成 分配给这个机台未报工的最小时间
        List<Produce> fproduce = produceMapper.producemindate(machineId);
        if(fproduce!=null&&fproduce.size()>0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = sdf.format(fproduce.get(0).getCreateTime());
            params.put("createTime", dateString);

            produce.setParams(params);
           fmproduces = produceMapper.fmtakeMachine(produce);
        }else{//没有待报工的
            //查待取板最小时间
            List<Produce> waitproduce = produceMapper.waittakedate(machineId);
            if(waitproduce!=null&&waitproduce.size()>0){//有待取版
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = sdf.format(waitproduce.get(0).getCreateTime());
                params.put("createTime", dateString);

                produce.setParams(params);
                fmproduces = produceMapper.fmtakeMachine(produce);
            }
        }

        //内文已审核没制版的
        List<Produce> allproduces = produceMapper.allocationtakeMachine(produce);
        List<Produce> produceslist = new ArrayList<>();

        //内文待取板数据
        if (nwproduces != null && nwproduces.size() > 0) {
            if (ncount < num) {
                int i = 0;
                int kq = num - ncount;
                for (Produce produce1 : nwproduces) {
                    if (i < kq) {
                        produce1.setIstake(1);
                        produceslist.add(produce1);
                    } else {
                        produceslist.add(produce1);
                    }
                    i++;
                }
            } else {
                produceslist.addAll(nwproduces);
            }
        }

        //封面待取板数据
        if (fmproduces != null && fmproduces.size() > 0) {
                for (Produce produce1 : fmproduces) {
                        produce1.setIstake(1);
                        produceslist.add(produce1);
                }
        }
        produceslist.addAll(allproduces);

        //需要返回的取板集合
        List<Produce> qblist = new ArrayList<>();

        List<Produce> nwlist = produceslist.stream().filter(x -> x.getType().equals("2"))
                .sorted(Comparator.comparing(Produce::getIstake).reversed())
                .collect(Collectors.toList());//内文集合

        List<Produce> fmlist = produceslist.stream().filter(x -> x.getType().equals("1"))
                .sorted(Comparator.comparing(Produce::getIstake).reversed())
                .collect(Collectors.toList());//封面集合

        if (nwlist != null && nwlist.size() > 0) {
            int size = nwlist.size();
            List<Produce> s = nwlist.subList(0, size < num ? size : num);
            qblist.addAll(s);
        }
        if (fmlist != null && fmlist.size() > 0) {
            int size = fmlist.size();
            List<Produce> s = fmlist.subList(0,size);
            qblist.addAll(s);
        }

        qblist = qblist.stream().sorted(Comparator.comparing(Produce::getIstake).reversed())
                .collect(Collectors.toList());
        return getDataTable(qblist);
    }

    //查询可以领用的生产单
    @PostMapping(value = "/getUseProduce")
    public TableDataInfo getUseProduce(@RequestBody Map<String, String> params) {
        startPage(params);
        String machineId = params.get("machineId");//机台id
        List<Produce> produces = produceMapper.getUseProduce(machineId);
        return getDataTable(produces);
    }

    // 制版左侧选择列表
    @PostMapping(value = "/leftListZhi")
    public TableDataInfo leftListZhi(@RequestBody Map<String, String> params) {
        startPage(params);
        String produceNo = params.get("produceNo");//生产单编号
        //Start 20240605
//        String ids = "3,19,20";   // 已做版 3，内容审核通过 19,20 分配审核通过
//        List<String> list = Arrays.asList(ids.split(","));
//        TableDataInfo data = getDataTable(produceService.list(new QueryWrapper<Produce>().lambda()
//                .like(StringUtils.isNotEmpty(produceNo), Produce::getProduceNo, produceNo)
//                .in(Produce::getStatus, list)
//                .orderByDesc(Produce::getSubmitDate)
//        ));
        //新版制版角色可以选到补版的数据和新版做版的数据，如果选的补版数据，需要更新补版单的状态，已制版，旧版制版角色只能选旧版做版的数据
        //获取当前登录人的信息新版制版角色可以选到补版的数据和新版做版的数据
        Long userId = SecurityUtils.getUserId();//当前登录人用户ID
        //根据用户ID判断这个这个人是否拥有新版制版角色
        String roleKey = produceMapper.selectRoleKeyBuUserId(userId);
        List<Produce> produces = new ArrayList<>();
        if (userId == 1 || (StringUtils.isNotEmpty(roleKey) && roleKey.equals("xbzb"))) {//新版做版
            produces = produceMapper.selectProduceList(produceNo);
        } else if (StringUtils.isNotEmpty(roleKey) && roleKey.equals("jbzb")) { //旧版做版
            produces = produceMapper.selectProduceListOld(produceNo);
        }
        TableDataInfo data = getDataTable(produces);
        //End
        return data;
    }


    // 制版右边根据左侧选择查询数据
    @PostMapping(value = "/rightListZhi")
    public TableDataInfo rightListZhi(@RequestBody Map<String, String> params) {
        String pid = params.get("pid");
        Long userId = SecurityUtils.getUserId();//当前登录人用户ID
        //根据用户ID判断这个这个人是否拥有新版制版角色
        String roleKey = produceMapper.selectRoleKeyBuUserId(userId);
        List<ProducePrint> producePrints = new ArrayList<>();
        if (userId == 1 || (StringUtils.isNotEmpty(roleKey) && roleKey.equals("xbzb"))) {//新版做版
            //根据生产单ID过滤数据
            producePrints = produceMapper.selectNewPrintListByProduceId(pid);
        } else if (StringUtils.isNotEmpty(roleKey) && roleKey.equals("jbzb")) { //旧版做版
            producePrints = produceMapper.selectOldPrintListByProduceId(pid);
        }
        //producePrintList
        TableDataInfo data = getDataTable(producePrints);
        return data;
    }


    //根据状态查询主表
    @PostMapping(value = "/getProduceStatelist")
    public TableDataInfo getProduceStatelist() {
        List<Produce> d = produceMapper.selectProduce();
        return getDataTable(d);
    }

    //查询剩余量最少的机台
    @PostMapping(value = "/getTaskLeast")
    public TableDataInfo getTaskLeast(@RequestBody Map<String, String> params) {
        String model = params.get("model");//平张/卷筒
        String size = params.get("size");
        MesMachine m = new MesMachine();
        m.setModel(model);
        m.setSize(size);
        List<MesMachine> machine = produceMapper.getTaskLeast(m);
        return getDataTable(machine);
    }

    //查询机台任务量
    @PostMapping(value = "/getMachineTask")
    public TableDataInfo getMachineTask(@RequestBody Map<String, Object> params) {
//        String machineName = params.get("machineName");//机台名称
//        String workshopName = params.get("workshopName");//车间名称
//        Date startDate = params.get("startDate");//开始时间
//        Date endDate = params.get("endDate");//车间名称

        MachineTask m = new MachineTask();
        PageHelper.startPage((Integer) params.get("pageNum"), (Integer) params.get("pageSize"));
        String machineState = (String) params.get("machineState");//完成状态
        if (Objects.equals(machineState, "2")) {//完成状态
            m.setParams(params);
            List<MachineTask> machineTask = produceMapper.getMachineTask(m);
            if(machineTask.size()>0) {
                MachineTask entity = produceMapper.getMachineTaskSum(m);
                machineTask.get(0).setPrintAmountSum(entity.getPrintAmountSum());
                machineTask.get(0).setTotalSum(entity.getTotalSum());
            }
            return getDataTable(machineTask);
        } else {
            m.setParams(params);
            List<MachineTask> machineTask = produceMapper.getnotMachineTask(m);
             if(machineTask.size()>0) {
              MachineTask entity = produceMapper.getnotMachineTaskSum(m);
                 machineTask.get(0).setPrintAmountSum(entity.getPrintAmountSum());
                 machineTask.get(0).setTotalSum(entity.getTotalSum());
             }
            return getDataTable(machineTask);
        }
    }

    //装订机台任务量
    @PostMapping(value = "/bindingMachineTask")
    public TableDataInfo bindingMachineTask(@RequestBody Map<String, Object> params) {
        MachineTask m = new MachineTask();
        PageHelper.startPage((Integer) params.get("pageNum"), (Integer) params.get("pageSize"));
        String machineState = (String) params.get("machineState");//完成状态
        if (Objects.equals(machineState, "2")) {//完成状态
            m.setParams(params);
            List<MachineTask> machineTask = produceMapper.bindingTask(m);//bindingMachineTask(m);
            return getDataTable(machineTask);
        } else {
            m.setParams(params);
            List<MachineTask> machineTask = produceMapper.bindingnotTask(m);//bindingTask(m);
            return getDataTable(machineTask);
        }
    }

    //根据新旧版查询产品信息表
    @PostMapping(value = "/getProduct")
    public AjaxResult getProduct(@RequestBody Map<String, String> params) {
        String pid = params.get("produceId");
        String newPast = params.get("newPast");
        Produce produce = produceService.getById(pid);
        List<ProduceProduct> produceProductList = produceProductService.list(new QueryWrapper<ProduceProduct>().lambda().eq(ProduceProduct::getProduceId, produce.getProduceId()).eq(StringUtils.isNotEmpty(newPast), ProduceProduct::getNewPast, newPast).orderByAsc(ProduceProduct::getProductNo));
        List<ProducePaper> producePaperList = producePaperService.list(new QueryWrapper<ProducePaper>().lambda().eq(ProducePaper::getProduceId, produce.getProduceId()).orderByAsc(ProducePaper::getPaperNo));
        List<ProducePrint> producePrintList = producePrintService.list(new QueryWrapper<ProducePrint>().lambda().eq(ProducePrint::getProduceId, produce.getProduceId()).orderByAsc(ProducePrint::getPrintProduceNo));
        List<ProduceCovering> produceCoveringList = produceCoveringService.list(new QueryWrapper<ProduceCovering>().lambda().eq(ProduceCovering::getProduceId, produce.getProduceId()).orderByAsc(ProduceCovering::getProduceCoveringNo));
        List<ProducePiece> producePieceList = producePieceService.list(new QueryWrapper<ProducePiece>().lambda().eq(ProducePiece::getProduceId, produce.getProduceId()).orderByAsc(ProducePiece::getProducePieceNo));
        produce.setProduceProductList(produceProductList);
        produce.setProducePaperList(producePaperList);
        produce.setProducePrintList(producePrintList);
        produce.setProduceCoveringList(produceCoveringList);
        produce.setProducePieceList(producePieceList);

        return AjaxResult.success("查询成功", produce);
    }

    @PostMapping(value = "/getpubNo")
    public AjaxResult getpubNo() {
//        int isnew = configMapper.getYearMaxisNew();
//        LocalDate currentDate = LocalDate.now();
//        String year = String.valueOf(currentDate.getYear());//获取当前年份
//        String xlh = PinYinUtils.sequence(isnew);//出版编号
//        String pubno = year + "-" + xlh;
//        return AjaxResult.success("获取成功", pubno);

        Produce produce1 = configMapper.getYearMaxisNew();
        if (produce1.getYear() == 0) {
            Calendar calendar = Calendar.getInstance();
            int currentYear = calendar.get(Calendar.YEAR);
            int nextYear = currentYear + 1;
            String pubNo = nextYear + "-0001";
            return AjaxResult.success("获取成功", pubNo);
        } else {
            String code = PinYinUtils.sequence(produce1.getNum());
            String pubNo = produce1.getYear() + "-" + code;
            return AjaxResult.success("获取成功", pubNo);
        }
    }


    @PostMapping(value = "/add")
    @Transactional
    public AjaxResult add(@RequestBody Produce produce) {
        if (produce.getProduceId() == null) {
            produce.setProduceId(UUID.randomUUID().toString().replace("-", ""));
            produce.setCreateBy(SecurityUtils.getUsername());
            Date currDate = DateUtils.getNowDate();
            produce.setCreateTime(currDate);
            produce.setIsSuspend("2");
            produce.setIsFp(null);
//            produce.setUrgentDate(produce.getDeliverDate());//加急交货日期等于默认交货日期
            // produce.setSubmitDate(currDate);
            Map<String, Object> map = new HashMap<>();
            map.put("columnName", "produce_no");
            map.put("tableName", "mes_produce");
            map.put("type", produce.getType());
            int maxNum = configMapper.getProduceMouthMaxId(map);
            if (Objects.equals(produce.getType(), "1")) {
                String code = PinYinUtils.getProduce(maxNum);
                produce.setProduceNo("FM" + code);
            } else {
                String code = PinYinUtils.getProduce(maxNum);
                produce.setProduceNo(code);
            }
        } else {
            produce.setUpdateTime(DateUtils.getNowDate());
            produce.setUpdateBy(SecurityUtils.getUsername());

//            // 修改出版编号逻辑
//            if (Objects.equals(produce.getIsNew(), "1")) {//修改时如果是新版
//                Produce producebefore = produceService.getById(produce.getProduceId());
//                if (Objects.equals(producebefore.getIsNew(), "2")) {//修改前为旧版
//
//                    Produce produce1 = configMapper.getYearMaxisNew();
//                    if (produce1.getYear() == 0) {
//                        Calendar calendar = Calendar.getInstance();
//                        int currentYear = calendar.get(Calendar.YEAR);
//                        int nextYear = currentYear + 1;
//                        String pubNo = nextYear + "-0001";
//                        produce.setPubNo(pubNo);
//                    } else {
//                        String code = PinYinUtils.sequence(produce1.getNum());
//                        String pubNo = produce1.getYear() + "-" + code;
//                        produce.setPubNo(pubNo);
//                    }
//                }
//            }
        }
        boolean isJoinFm = false; // 是否关联封面生产单
        if (produce.getProduceProductList() != null && produce.getProduceProductList().size() != 0) {
            int xh = 0;
            for (ProduceProduct produceProduct : produce.getProduceProductList()) {
                String xlh = PinYinUtils.sequence(xh);//序列号
                produceProduct.setSort(xh + 1);
                produceProduct.setProduceId(produce.getProduceId());
                produceProduct.setProductNo(produce.getProduceNo() + "CP" + xlh);
                produceProduct.setCreateBy(SecurityUtils.getUsername());
                produceProduct.setCreateTime(DateUtils.getNowDate());
                // 只有封面调整该数量
                if (StringUtils.isNotEmpty(produce.getType()) && "1".equals(produce.getType())) {
                    produceProduct.setProduceCountYu(produceProduct.getProduceCount());
                }
                xh = xh + 1;
                // 有值证明有关联封面生产单
                if (StringUtils.isNotEmpty(produceProduct.getProduceIds())) {
                    isJoinFm = true;
                }
            }
        }
        if (produce.getProducePaperList() != null && produce.getProducePaperList().size() != 0) {
            int xh = 0;
            for (ProducePaper producePaper : produce.getProducePaperList()) {
                String xlh = PinYinUtils.sequence(xh);//序列号
                producePaper.setProduceId(produce.getProduceId());
                producePaper.setPaperProduceNo(produce.getProduceNo() + "ZZ" + xlh);
                producePaper.setCreateBy(SecurityUtils.getUsername());
                producePaper.setCreateTime(DateUtils.getNowDate());
                xh = xh + 1;
            }
        }
        String Printid = "";
        if (produce.getProducePrintList() != null && produce.getProducePrintList().size() != 0) {
            int xh = 0;

            for (ProducePrint producePrint : produce.getProducePrintList()) {
                if (Objects.equals(produce.getType(), "1") && (producePrint.getPrintId() == null || producePrint.getPrintId().isEmpty())) {
                    Printid = UUID.randomUUID().toString().replace("-", "");
                    producePrint.setPrintId(Printid);
                }
                String xlh = PinYinUtils.sequence(xh);//序列号
                producePrint.setSort(xh + 1);
                producePrint.setProduceId(produce.getProduceId());
                producePrint.setPrintProduceNo(produce.getProduceNo() + "YS" + xlh);
                producePrint.setCreateBy(SecurityUtils.getUsername());
                producePrint.setCreateTime(DateUtils.getNowDate());
                xh = xh + 1;
            }
        }
        if (produce.getProduceCoveringList() != null && produce.getProduceCoveringList().size() != 0) {
            int xh = 0;
            for (ProduceCovering produceCovering : produce.getProduceCoveringList()) {
                String xlh = PinYinUtils.sequence(xh);//序列号
                produceCovering.setProduceId(produce.getProduceId());
                produceCovering.setProduceCoveringNo(produce.getProduceNo() + "SCFM" + xlh);
                produceCovering.setCreateBy(SecurityUtils.getUsername());
                produceCovering.setCreateTime(DateUtils.getNowDate());
                xh = xh + 1;
            }
        }
        if (produce.getProducePieceList() != null && produce.getProducePieceList().size() != 0) {
            int xh = 0;

            for (ProducePiece producePiece : produce.getProducePieceList()) {
                if (Printid != "") {
                    producePiece.setPrintId(Printid);
                }
                String xlh = PinYinUtils.sequence(xh);//序列号
                producePiece.setSort(xh + 1);
                producePiece.setProduceId(produce.getProduceId());
                producePiece.setProducePieceNo(produce.getProduceNo() + "TS" + xlh);
                producePiece.setCreateBy(SecurityUtils.getUsername());
                producePiece.setCreateTime(DateUtils.getNowDate());
                xh = xh + 1;
            }
        }
        produceService.saveOrUpdate(produce);
        // 只有内文生产单才修改
        if ("2".equals(produce.getType())) {
            if (isJoinFm) {
                // 修改对应的主表
                produceService.update(new UpdateWrapper<Produce>().set("is_join_fm", "1").eq("produce_id", produce.getProduceId()));
            } else {
                // 修改对应的主表
                produceService.update(new UpdateWrapper<Produce>().set("is_join_fm", "0").eq("produce_id", produce.getProduceId()));
            }
        }
        if (produce.getProduceProductList() != null && produce.getProduceProductList().size() != 0) {
            produceProductService.remove(new QueryWrapper<ProduceProduct>().lambda().eq(ProduceProduct::getProduceId, produce.getProduceId()));
            produceProductService.saveBatch(produce.getProduceProductList());
        }
        if (produce.getProducePaperList() != null && produce.getProducePaperList().size() != 0) {
            producePaperService.remove(new QueryWrapper<ProducePaper>().lambda().eq(ProducePaper::getProduceId, produce.getProduceId()));
            producePaperService.saveBatch(produce.getProducePaperList());
        }
        if (produce.getProducePrintList() != null && produce.getProducePrintList().size() != 0) {
            producePrintService.remove(new QueryWrapper<ProducePrint>().lambda().eq(ProducePrint::getProduceId, produce.getProduceId()));
            producePrintService.saveBatch(produce.getProducePrintList());
        }
        if (produce.getProduceCoveringList() != null && produce.getProduceCoveringList().size() != 0) {
            produceCoveringService.remove(new QueryWrapper<ProduceCovering>().lambda().eq(ProduceCovering::getProduceId, produce.getProduceId()));
            produceCoveringService.saveBatch(produce.getProduceCoveringList());
        }
        if (produce.getProducePieceList() != null && produce.getProducePieceList().size() != 0) {
            producePieceService.remove(new QueryWrapper<ProducePiece>().lambda().eq(ProducePiece::getProduceId, produce.getProduceId()));
            producePieceService.saveBatch(produce.getProducePieceList());
        }
        mesOrderProductService.update(new UpdateWrapper<MesOrderProduct>().lambda().set(MesOrderProduct::getProduceId, null).eq(MesOrderProduct::getProduceId, produce.getProduceId()));

        if (produce.getProduceProductList() != null && produce.getProduceProductList().size() != 0) {
            List<String> orderIds = produce.getProduceProductList().stream().map(ProduceProduct::getOrderProductId).collect(Collectors.toList());
            mesOrderProductService.update(new UpdateWrapper<MesOrderProduct>().lambda().set(MesOrderProduct::getProduceId, produce.getProduceId()).in(MesOrderProduct::getPid, orderIds));
        }
        return AjaxResult.success("添加成功", produce.getProduceId());
    }

    @PostMapping("/edit")
    @Transactional
    public AjaxResult edit(@RequestBody Produce produce) {
        if (StringUtils.isEmpty(produce.getProduceId())) {
            return AjaxResult.error("未获取到主表主键");
        }
        // 产品信息
        if (produce.getProduceProductList() != null && produce.getProduceProductList().size() > 0) {
            produceProductService.updateBatchById(produce.getProduceProductList());
        }
        // 纸张信息
        if (produce.getProducePaperList() != null && produce.getProducePaperList().size() > 0) {
            // 删除历史数据
            producePaperService.remove(new QueryWrapper<ProducePaper>().eq("produce_id", produce.getProduceId()));
            // 获取最大的编号
            int xh = 0;
            for (ProducePaper e : produce.getProducePaperList()) {
                if (StringUtils.isNotEmpty(e.getPaperProduceNo())) {
                    String substring = e.getPaperProduceNo().substring(e.getPaperProduceNo().length() - 4);
                    int integer = Integer.valueOf(substring);
                    if (integer > xh) {
                        xh = integer;
                    }
                }
            }
            for (ProducePaper producePaper : produce.getProducePaperList()) {
                producePaper.setProduceId(produce.getProduceId());
                producePaper.setCreateBy(SecurityUtils.getUsername());
                producePaper.setCreateTime(DateUtils.getNowDate());
                if (StringUtils.isEmpty(producePaper.getPaperProduceNo())) {
                    String xlh = PinYinUtils.sequence(xh);//序列号
                    producePaper.setPaperProduceNo(produce.getProduceNo() + "ZZ" + xlh);
                    xh = xh + 1;
                }
            }
            // 新增数据
            producePaperService.saveBatch(produce.getProducePaperList());
        }
        // 印刷管理
        if (produce.getProducePrintList() != null && produce.getProducePrintList().size() > 0) {
            producePrintService.updateBatchById(produce.getProducePrintList());
        }
        // 贴数管理
        if (produce.getProducePieceList() != null && produce.getProducePieceList().size() > 0) {
            producePieceService.updateBatchById(produce.getProducePieceList());
        }
        return AjaxResult.success();
    }


    @PostMapping(value = "/updateMakeStatus")
    @Transactional
    public AjaxResult updateMakeStatus(@RequestBody Produce produce) {
        //版房审核后分配机台
        String pid = produce.getProduceId();
//        Allocation(pid);
        String MakeStatus = produce.getMakeStatus();
        String Status = produce.getStatus();
        produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getMakeStatus, MakeStatus)
                .set(Produce::getStatus, Status)
                .eq(Produce::getProduceId, pid));

        //更新印刷管理数据
        if (produce.getProducePrintList() != null && produce.getProducePrintList().size() != 0) {
            producePrintService.remove(new QueryWrapper<ProducePrint>().lambda().eq(ProducePrint::getProduceId, produce.getProduceId()));
            producePrintService.saveBatch(produce.getProducePrintList());
        }

        //判断细表中是否做版 1:是 2:否，如果是
        if (produce.getProducePrintList() != null && produce.getProducePrintList().size() > 0) {
            List<ProducePrint> producePrints = produce.getProducePrintList();
            List<ProducePrint> producePrintNews = producePrints.stream().filter(x -> x.getNewPast().equals("1"))
                    .collect(Collectors.toList());//做版 新版
            List<ProducePrint> producePrintOlds = producePrints.stream().filter(x -> x.getNewPast().equals("2"))
                    .collect(Collectors.toList());//做版 旧版

            if (producePrintNews != null && producePrintNews.size() > 0) {
                MesMakeVersion mesMakeVersionNew = new MesMakeVersion();
                List<MesMakeversionDetail> mesMakeversionDetails = new ArrayList<>();
                for (ProducePrint producePrint : producePrintNews) {
                    mesMakeVersionNew.setMakeBy(SecurityUtils.getUsername());//做版人 //producePrint.getMakeBy()
                    mesMakeVersionNew.setIsNew(producePrint.getNewPast());//新旧版
                    mesMakeVersionNew.setStatus(2);//已提交
                    mesMakeVersionNew.setMakeDate(new Date()); //做版日期
                    mesMakeVersionNew.setCreateBy(SecurityUtils.getUsername());//创建人 //producePrint.getMakeBy()
                    mesMakeVersionNew.setCreateTime(new Date());//创建日期

                    MesMakeversionDetail mesMakeversionDetail = new MesMakeversionDetail();
                    mesMakeversionDetail.setProduceNo(produce.getProduceNo());//生产单编号
                    mesMakeversionDetail.setPubNo(produce.getPubNo());//出版编号
                    mesMakeversionDetail.setPrintProduceNo(producePrint.getPrintProduceNo());//印刷序列号
                    mesMakeversionDetail.setBreed(producePrint.getBreed());
                    mesMakeversionDetail.setComposition(producePrint.getComposition());//组成
                    mesMakeversionDetail.setSheet(producePrint.getSheet());//印张
                    mesMakeversionDetail.setPrintAmount(producePrint.getPrintAmount());//印数
                    mesMakeversionDetail.setPrintColour(producePrint.getPrintColour());//印色
                    mesMakeversionDetail.setSheetAmount(producePrint.getSheetAmount());//版材数量
                    mesMakeversionDetail.setSheetSize(producePrint.getSheetSize());//版材尺寸
                    mesMakeversionDetail.setRemark(producePrint.getHouseRemark());//备注
                    mesMakeversionDetail.setProducePrintId(producePrint.getPrintId());
                    mesMakeversionDetails.add(mesMakeversionDetail);

                }
                if (mesMakeVersionNew != null && StringUtils.isNotEmpty(mesMakeVersionNew.getMakeBy())) {
                    mesMakeVersionNew.setMesMakeversionDetailList(mesMakeversionDetails);
                    mesMakeVersionService.insertMesMakeVersion(mesMakeVersionNew);

                }
            }

            if (producePrintOlds != null && producePrintOlds.size() > 0) {
                MesMakeVersion mesMakeVersionOld = new MesMakeVersion();
                List<MesMakeversionDetail> mesMakeversionDetailOlds = new ArrayList<>();
                for (ProducePrint producePrint : producePrintOlds) {
                    mesMakeVersionOld.setMakeBy(producePrint.getMakeBy());//做版人
                    mesMakeVersionOld.setIsNew(producePrint.getNewPast());//新旧版
                    mesMakeVersionOld.setStatus(2);//已提交
                    mesMakeVersionOld.setMakeDate(new Date()); //做版日期
                    mesMakeVersionOld.setCreateBy(producePrint.getMakeBy());//创建人
                    mesMakeVersionOld.setCreateTime(new Date());//创建日期

                    MesMakeversionDetail mesMakeversionDetail = new MesMakeversionDetail();
                    mesMakeversionDetail.setProduceNo(produce.getProduceNo());//生产单编号
                    mesMakeversionDetail.setPubNo(produce.getPubNo());//出版编号
                    mesMakeversionDetail.setPrintProduceNo(producePrint.getPrintProduceNo());//印刷序列号
                    mesMakeversionDetail.setBreed(producePrint.getBreed());
                    mesMakeversionDetail.setComposition(producePrint.getComposition());//组成
                    mesMakeversionDetail.setSheet(producePrint.getSheet());//印张
                    mesMakeversionDetail.setPrintAmount(producePrint.getPrintAmount());//印数
                    mesMakeversionDetail.setPrintColour(producePrint.getPrintColour());//印色
                    mesMakeversionDetail.setSheetAmount(producePrint.getSheetAmount());//版材数量
                    mesMakeversionDetail.setSheetSize(producePrint.getSheetSize());//版材尺寸
                    mesMakeversionDetail.setRemark(producePrint.getHouseRemark());//备注
                    mesMakeversionDetail.setProducePrintId(producePrint.getPrintId());
                    mesMakeversionDetailOlds.add(mesMakeversionDetail);
                }
                if (mesMakeVersionOld != null && StringUtils.isNotEmpty(mesMakeVersionOld.getMakeBy())) {
                    mesMakeVersionOld.setMesMakeversionDetailList(mesMakeversionDetailOlds);
                    mesMakeVersionService.insertMesMakeVersion(mesMakeVersionOld);
                }
            }
        }

//
        return AjaxResult.success("更新成功");
    }


    @PostMapping(value = "/updateStatus")
    @Transactional
//    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxResult updateStatus(@RequestBody Map<String, String> params) {

        String pid = params.get("pid");
        String status = params.get("status");
        Produce produce = produceService.getById(pid);
        produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getStatus, status).eq(Produce::getProduceId, pid));
        if ("0".equals(status) || "-2".equals(status)) {
            mesOrderProductService.update(new UpdateWrapper<MesOrderProduct>().lambda().set(MesOrderProduct::getProduceId, null).eq(MesOrderProduct::getProduceId, pid));
            //20240401 修改机台分配的贴数Status=1
            produceMapper.updateProducePieceMachineStatus(pid);
            if ("-2".equals(status)) {
                produceMapper.updateStatusBom(pid);
            }
        }
        if ("2".equals(status)) {//提交更改下单时间
//            produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getSubmitDate, new Date())
//                    .eq(Produce::getProduceId, pid));
            // 提交修改BOM单的印刷次数加 1
            updateBomOrderPrintNum(pid, 1);
            //20240412 增加审核按钮，现在提交是提交至版房，即版房能看到这条生产单，版房审核后再分配机台 新增加方法updateMakeStatus
if(Objects.equals(produce.getType(), "1")) {
    //判断是否分配
    if(produce.getIsFp()==null || !produce.getIsFp().equals("1")){
        produceService.AllocationMachine(pid);
    }

}else{
    //内文分配目录
    produceService.MlMachine(pid);
}
        } else {
            // 印刷次数减 1
            updateBomOrderPrintNum(pid, -1);
        }

        //把封面生产单明细中改订单号设置为一选择

        produceMapper.updateFMProduceDetail(produce);

        return AjaxResult.success("更新成功");
    }

    @PostMapping(value = "/updateMultipleStatus")
    @Transactional
    public AjaxResult updateMultipleStatus(@RequestBody Map<String, String> params) {
        String ids = params.get("ids");
        String status = params.get("status");

        List<String> list = Arrays.asList(ids.split(","));
        produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getStatus, status).in(Produce::getProduceId, list));
        return AjaxResult.success("更新成功");
    }



    //根据贴数单查询分配的机台
    @PostMapping(value = "/getProducePieceMachine")
    public TableDataInfo getProducePieceMachine(@RequestBody Map<String, String> params) {
        String pieceId = params.get("pieceId");
        List<MesProducePieceMachine> machine = produceMapper.ProducePieceMachinelist(pieceId);
//       List<MesProducePieceMachine> data= mesProducePieceMachineService.list(
//               new QueryWrapper<MesProducePieceMachine>());
        return getDataTable(machine);
    }

    //根据订单Id获取封面生产单信息
    @PostMapping(value = "/getProduceCovingByOrderId")
    public TableDataInfo getProduceCovingByOrderId(@RequestBody Map<String, String> params) {
        String orderId = params.get("orderId");
        String produceNo = params.get("produceNo");
        Produce produce = new Produce();
        produce.setOrderId(orderId);
        produce.setProduceNo(produceNo);
        List<Produce> produceList = produceMapper.getProduceCovingByOrderId(produce);
        return getDataTable(produceList);
    }

    @PostMapping(value = "/updateProducePieceMachine")
    public AjaxResult updateProducePieceMachine(@RequestBody Map<String, String> params) {
        String printId = params.get("printId");//
        String pieceId = params.get("pieceId");
        String machineId = params.get("machineId");
        String machineType = params.get("machineType");
        List<ProducePiece> data = producePieceService.list(new QueryWrapper<ProducePiece>().lambda()
                .eq(StringUtils.isNotEmpty(printId), ProducePiece::getPrintId, printId)
                .eq(StringUtils.isNotEmpty(pieceId), ProducePiece::getPieceId, pieceId));
        if (data != null && data.size() != 0) {
            for (ProducePiece p : data) {
                mesProducePieceMachineService
                        .update(new UpdateWrapper<MesProducePieceMachine>().lambda()
                                .set(MesProducePieceMachine::getMachineId, machineId)
                                .eq(MesProducePieceMachine::getPieceId, p.getPieceId())
                                .eq(MesProducePieceMachine::getMachineType, machineType)
                        );
            }
        }
        return AjaxResult.success("更新成功");
    }


    @PostMapping(value = "/updateProcessStatus")
    public AjaxResult updateProcessStatus(@RequestBody Map<String, String> params) {
        String pid = params.get("pid");
        String processStatus = params.get("processStatus");
        produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getProcessStatus, processStatus).eq(Produce::getProduceId, pid));
        return AjaxResult.success("更新成功");
    }

    @PostMapping(value = "/updateUrgentDate")
    public AjaxResult updateUrgentDate(@RequestBody Map<String, String> params) throws ParseException {
        String pid = params.get("pid");
        String urgentNum = params.get("urgentNum");
        String urgentDate = params.get("urgentDate");
        LambdaUpdateWrapper<Produce> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Produce::getProduceId, pid); // 设置更新条件，例如按照id更新
        if(StringUtils.isNotEmpty(urgentDate)){
            updateWrapper.set(Produce::getUrgentDate, DateUtils.parseDate(urgentDate, "yyyy-MM-dd HH:mm:ss"));
        }else {
            updateWrapper.set(Produce::getUrgentDate, null);
        }
        if (StringUtils.isNotEmpty(urgentNum)) {
            updateWrapper.set(Produce::getUrgentNum, Double.parseDouble(urgentNum)); // 如果fieldValue不为空，则更新该字段
        }else {
            updateWrapper.set(Produce::getUrgentNum, null);
        }
        produceService.update(updateWrapper);
//        produceService.update(new UpdateWrapper<Produce>().lambda()
//                .set(Produce::getUrgentDate, DateUtils.parseDate(urgentDate, "yyyy-MM-dd HH:mm:ss"))
//                .eq(Produce::getProduceId, pid));
        List<ProducePiece> producePieceList = producePieceService.list(new QueryWrapper<ProducePiece>().lambda().eq(ProducePiece::getProduceId, pid).orderByAsc(ProducePiece::getProducePieceNo));
        // 加急的预计交货日期更新到任务分配的中间表
        for (ProducePiece producePiece : producePieceList) {
            mesProducePieceMachineService.update(new UpdateWrapper<MesProducePieceMachine>().lambda()
                    .set(MesProducePieceMachine::getExpectTime, urgentDate)
                    .eq(MesProducePieceMachine::getPieceId, producePiece.getPieceId())
            );
        }
        return AjaxResult.success("更新成功");
    }


    //更新换片内容
    @PostMapping(value = "/updateChangePiece")
    public AjaxResult updateChangePiece(@RequestBody Map<String, String> params) throws ParseException {
        String pid = params.get("pid");
        //String changePiece = params.get("changePiece");
        String remark = params.get("remark");
        produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getRemark, remark).eq(Produce::getProduceId, pid));
        List<ProducePiece> producePieceList = producePieceService.list(new QueryWrapper<ProducePiece>().lambda().eq(ProducePiece::getProduceId, pid).orderByAsc(ProducePiece::getProducePieceNo));

        return AjaxResult.success("更新成功");
    }

    @PostMapping(value = "/getById")
    public AjaxResult getById(@RequestBody Map<String, String> params) {
        String pid = params.get("pid");
        String makeStatus = params.get("makeStatus");
        Produce produce = produceService.getById(pid);
        String machineId = params.get("machineId"); //机台Id
        String isMake = params.get("isMake"); //印刷单是否做版
        List<ProducePrint> producePrintList = new ArrayList<>();
        List<ProduceProduct> produceProductList = produceProductService.list(new QueryWrapper<ProduceProduct>().lambda()
                .eq(ProduceProduct::getProduceId, produce.getProduceId())
                .orderByAsc(ProduceProduct::getProductNo));
        //.orderByAsc(ProduceProduct::getBreed));
        List<ProducePaper> producePaperList = producePaperService.list(new QueryWrapper<ProducePaper>().lambda().eq(ProducePaper::getProduceId, produce.getProduceId()).orderByAsc(ProducePaper::getPaperNo));
        if (Objects.equals(isMake, "2")) {
            producePrintList = producePrintService.list(new QueryWrapper<ProducePrint>().lambda()
                    .eq(ProducePrint::getProduceId, produce.getProduceId())
                    .eq(StringUtils.isNotEmpty(makeStatus), ProducePrint::getMakeStatus, makeStatus)
                    .eq(ProducePrint::getIsMake, isMake)
                    .orderByAsc(ProducePrint::getPrintProduceNo));
            // .orderByAsc(ProducePrint::getBreed).orderByAsc(ProducePrint::getLabeling));
        } else if (Objects.equals(isMake, "1")) {
            producePrintList = producePrintService.list(new QueryWrapper<ProducePrint>().lambda()
                    .eq(ProducePrint::getProduceId, produce.getProduceId())
                    .eq(StringUtils.isNotEmpty(makeStatus), ProducePrint::getMakeStatus, makeStatus)
                    .isNull(ProducePrint::getIsMake)
                    .orderByAsc(ProducePrint::getPrintProduceNo));
            //.orderByAsc(ProducePrint::getBreed).orderByAsc(ProducePrint::getLabeling));
        } else {
            producePrintList = producePrintService.list(new QueryWrapper<ProducePrint>().lambda()
                    .eq(ProducePrint::getProduceId, produce.getProduceId())
                    .eq(StringUtils.isNotEmpty(makeStatus), ProducePrint::getMakeStatus, makeStatus)
                    //.orderByAsc(ProducePrint::getBreed).orderByAsc(ProducePrint::getLabeling));
                    .orderByAsc(ProducePrint::getPrintProduceNo));
        }

        List<ProduceCovering> produceCoveringList = produceCoveringService.list(new QueryWrapper<ProduceCovering>().lambda().eq(ProduceCovering::getProduceId, produce.getProduceId()).orderByAsc(ProduceCovering::getProduceCoveringNo));
        List<ProducePiece> producePieceList = producePieceService.list(new QueryWrapper<ProducePiece>().lambda()
                .eq(ProducePiece::getProduceId, produce.getProduceId())
                .orderByAsc(ProducePiece::getProducePieceNo));
        //.orderByAsc(ProducePiece::getBreed).orderByAsc(ProducePiece::getPieceView));


        for (ProducePiece producePiece : producePieceList) {
//            // 生产单报工查询累计上报数量
//            MesProducePieceMachine producePieceMachine = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
//                    .eq(MesProducePieceMachine::getPieceId, producePiece.getPieceId())
//                    .eq(MesProducePieceMachine::getMachineId, machineId)
//                    .last("LIMIT 1")
//            );
//            if (producePieceMachine != null) {
//                producePiece.setTotalNum(producePieceMachine.getTotal());
//            }

//            // 统计查询该贴的累计上报数量
//            List<ReportWork> list = reportWorkService.list(new QueryWrapper<ReportWork>().lambda().eq(ReportWork::getPieceId, producePiece.getPieceId()));
//            BigDecimal temp = BigDecimal.ZERO;
//            BigDecimal finshNum = BigDecimal.ZERO;
//            for (ReportWork totalWork : list) {
//                finshNum=totalWork.getFinishNum()==null? BigDecimal.ZERO:totalWork.getFinishNum();
//                temp = temp.add(finshNum);
//            }
//            producePiece.setTotalNum(temp);

            List<MesProducePieceMachine> machine = produceMapper.ProducePieceMachinelist(producePiece.getPieceId());
            if (machine != null && machine.size() != 0) {
                for (MesProducePieceMachine piece : machine) {
                    String type = piece.getMachineType();
                    producePiece.setMachineId(piece.getMachineId());
                    if (Objects.equals(type, "2")) {
                        producePiece.setPrintMachine(piece.getMachineName());//印刷机
                    }
                    if (Objects.equals(type, "3")) {
                        producePiece.setBindingMachine(piece.getMachineName());//装订机
                    }
                    if (Objects.equals(type, "4")) {
                        producePiece.setFoldMachine(piece.getMachineName());//折页机
                    }
                    if (Objects.equals(type, "5")) {
                        producePiece.setWhitecuttingMachine(piece.getMachineName());//白纸裁切机
                    }
                    if (Objects.equals(type, "6")) {
                        producePiece.setCovercuttingMachine(piece.getMachineName());//封面裁切机
                    }
                    if (Objects.equals(type, "7")) {
                        producePiece.setCoveringMachine(piece.getMachineName());//覆膜机
                    }
                }
            }
        }

        if (producePrintList != null && producePrintList.size() != 0 && producePieceList != null && producePieceList.size() != 0) {
            for (ProducePrint print : producePrintList) {
                //print.getPaperNo() 根据纸张编码查询厂商
                MesPaper mesPaper = paperMapper.selectMesPaperNameByCode(print.getPaperNo());
                String firmShort = mesPaper != null ? mesPaper.getFirmShort() : ""; //厂商简称
                String paperName = mesPaper != null ? mesPaper.getName() : "";// 纸张名称
                print.setFirmShort(firmShort);
                print.setPaperName(paperName);
                List<ProducePiece> pieceList = producePieceList.stream().filter(it -> it.getPrintId().equals(print.getPrintId()))
                        .collect(Collectors.toList());
                if (pieceList != null && pieceList.size() != 0) {
                    ProducePiece piece = pieceList.get(0);
                    print.setWhitecuttingMachine(piece.getWhitecuttingMachine());
                    print.setBindingMachine(piece.getBindingMachine());
                    print.setCoveringMachine(piece.getCoveringMachine());
                    print.setFoldMachine(piece.getFoldMachine());
                    print.setCovercuttingMachine(piece.getCovercuttingMachine());
                    print.setPrintMachine(piece.getPrintMachine());
                    print.setMachineId(piece.getMachineId());
                }
            }
        }


        if (producePaperList != null && producePaperList.size() != 0) {
            for (ProducePaper paper : producePaperList) {
                MesPaper p = mesPaperService.selectMesPaperById(Long.valueOf(paper.getPaperInfoId()));
                paper.setPackageType(p.getPackageType());
            }
        }

        // 其他报工引用，需要过滤数据
        if (StringUtils.isNotEmpty(params.get("otherReport"))) {
            // 获取核算类型，根据核算类型查询累计完成数量
            String s = params.get("otherReport");
            List<OtherReportDetail> detailList = reportDetailService.list(new QueryWrapper<OtherReportDetail>().eq("account_type", s).isNotNull("product_id"));
            Map<String, List<OtherReportDetail>> listMap = detailList.stream().collect(Collectors.groupingBy(OtherReportDetail::getProductId));
            // 循环累计完成数量
            HashMap<String, BigDecimal> hashMap = new HashMap<>();
            for (String m : listMap.keySet()) {
                BigDecimal decimal = new BigDecimal(0);
                for (OtherReportDetail detail : listMap.get(m)) {
                    // 完成数量
                    BigDecimal finshNum = detail.getFinshNum() == null ? new BigDecimal(0) : new BigDecimal(detail.getFinshNum().toString());
                    decimal = decimal.add(finshNum);
                }
                hashMap.put(m, decimal);
            }
            ArrayList<ProduceProduct> produceProducts = new ArrayList<>();
            // 循环产品信息，查询其他报工累计完成数量是否已经达到订单量
            for (ProduceProduct product : produceProductList) {
                // 获取订单数量
                BigDecimal produceCount = product.getProduceCount() == null ? new BigDecimal(0) : new BigDecimal(product.getProduceCount().toString());
                // 获取累计完成数量
                BigDecimal decimal = hashMap.get(product.getProductId()) == null ? new BigDecimal(0) : hashMap.get(product.getProductId());
                product.setTotalNum(decimal);
                // 其他报工 除八开卷裁切和书本裁切外 最大上报量+50
                if ("20".equals(s) || "19".equals(s)) {
                    product.setMaxNum(produceCount.subtract(decimal));
                } else {
                    product.setMaxNum(produceCount.subtract(decimal).add(new BigDecimal("50")));
                }
                // 如果累计完成数量>=0.99*订单数量，不能再选择到
                BigDecimal multiply = produceCount.multiply(new BigDecimal("0.99"));
                if (decimal.compareTo(multiply) < 0) {
                    produceProducts.add(product);
                }
            }
            produceProductList = new ArrayList<>();
            produceProductList.addAll(produceProducts);
        }

        produce.setProduceProductList(produceProductList);
        produce.setProducePaperList(producePaperList);
        produce.setProducePrintList(producePrintList);
        produce.setProduceCoveringList(produceCoveringList);
        produce.setProducePieceList(producePieceList);

        return AjaxResult.success("查询成功", produce);
    }

    @GetMapping(value = "/getByIdFilter")
    public AjaxResult getByIdFilter(ProducePiece params) {
        String pid = params.getProduceId();
        String makeStatus = "";
        String machineId = params.getMachineId(); //机台Id

        MesMachine mesMachine = mesMachineService.getById(machineId);
        String machineType = mesMachine.getType();

        Produce produce = produceService.getById(pid);
        List<ProduceProduct> produceProductList = produceProductService.list(new QueryWrapper<ProduceProduct>().lambda()
                .eq(ProduceProduct::getProduceId, produce.getProduceId()).
                orderByAsc(ProduceProduct::getBreed));
        List<ProducePaper> producePaperList = producePaperService.list(new QueryWrapper<ProducePaper>().lambda()
                .eq(ProducePaper::getProduceId, produce.getProduceId()).orderByAsc(ProducePaper::getPaperNo));

        List<ProducePrint> producePrintList = producePrintService.list(new QueryWrapper<ProducePrint>().lambda()
                .eq(ProducePrint::getProduceId, produce.getProduceId())
                .eq(StringUtils.isNotEmpty(makeStatus), ProducePrint::getMakeStatus, makeStatus)
                .orderByAsc(ProducePrint::getBreed).orderByAsc(ProducePrint::getLabeling));

        List<ProduceCovering> produceCoveringList = produceCoveringService.list(new QueryWrapper<ProduceCovering>().lambda()
                .eq(ProduceCovering::getProduceId, produce.getProduceId())
                .orderByAsc(ProduceCovering::getProduceCoveringNo));

        ProducePiece producePieceMode = new ProducePiece();
        producePieceMode.setProduceId(produce.getProduceId());
        producePieceMode.setMachineId(machineId);
        producePieceMode.setMachineType(machineType);

        if (Objects.equals(machineType, "2")) {
            producePieceMode.setPressState("2");//印刷机
        }
        if (Objects.equals(machineType, "3")) {
            producePieceMode.setBindingState("2");//装订机
        }
        if (Objects.equals(machineType, "4")) {
            producePieceMode.setFoldState("2");//折页机
        }
        if (Objects.equals(machineType, "5") || Objects.equals(machineType, "6")) {
            producePieceMode.setTrimmingState("2");//裁切机
        }
        if (Objects.equals(machineType, "7")) {
            producePieceMode.setCoveringState("2");//覆膜机
        }

//        List<String> ids = producePrintList.stream().map(it -> it.getPrintId()).collect(Collectors.toList());
//        List<ProducePiece> pieceList = producePieceService.list(new QueryWrapper<ProducePiece>().lambda()
//                .in(ProducePiece::getPrintId, ids));

        List<ProducePiece> producePieceList = produceMapper.ProducePieceList(producePieceMode);

        for (ProducePiece pieceItem : producePieceList) {
            ProducePrint producePrint = producePrintService.getOne(new QueryWrapper<ProducePrint>().lambda()
                    .eq(ProducePrint::getPrintId, pieceItem.getPrintId()));
            BigDecimal lossCoefficient = StringUtils.isEmpty(producePrint.getLossCoefficient()) ? BigDecimal.ZERO : new BigDecimal(producePrint.getLossCoefficient());
            pieceItem.setLossCoefficient(lossCoefficient);
        }

//        for (ProducePiece producePiece : producePieceList) {
//            // 生产单报工查询累计上报数量
//            MesProducePieceMachine producePieceMachine = producePieceMachineService.getOne(new QueryWrapper<MesProducePieceMachine>().lambda()
//                    .eq(MesProducePieceMachine::getPieceId, producePiece.getPieceId())
//                    .eq(MesProducePieceMachine::getMachineId, machineId)
//                    .last("LIMIT 1")
//            );
//            if (producePieceMachine != null) {
//                BigDecimal total = producePieceMachine.getTotal() == null ? BigDecimal.ZERO : producePieceMachine.getTotal();
//                BigDecimal amount = producePiece.getPrintAmount() == null ? BigDecimal.ZERO : producePiece.getPrintAmount();
//                BigDecimal surplus = amount.subtract(total);
//                surplus = surplus.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : surplus;
//                // 累计上报数
//                producePiece.setTotalNum(total);
//                // 改帖印数 - 累计上报数 = 最大允许上报数
//                producePiece.setMaxNum(surplus);
//            }
//        }

        if (producePaperList != null && producePaperList.size() != 0) {
            for (ProducePaper paper : producePaperList) {
                MesPaper p = mesPaperService.selectMesPaperById(Long.valueOf(paper.getPaperInfoId()));
                paper.setPackageType(p.getPackageType());
            }
        }
        produce.setProduceProductList(produceProductList);
        produce.setProducePaperList(producePaperList);
        produce.setProducePrintList(producePrintList);
        produce.setProduceCoveringList(produceCoveringList);
        produce.setProducePieceList(producePieceList);

        // 循环查询累计上报数量 和 最大允许上报量
        String errorMes = MesReportWork.selectMesReportTotalNum(produce, machineId, machineType, "");
        if (StringUtils.isNotEmpty(errorMes)) {
            return AjaxResult.error(errorMes);
        }

        return AjaxResult.success("查询成功", produce);
    }

    @GetMapping(value = "/getByIdFilterBind")
    public AjaxResult getByIdFilterBinding(ProduceProduct params) {
        String pid = params.getProduceId();
        String makeStatus = "";
        String machineId = params.getMachineId(); //机台Id
        String bindingType = params.getBindingType();

        MesMachine mesMachine = mesMachineService.getById(machineId);
        String machineType = mesMachine.getType();

        Produce produce = produceService.getById(pid);

        MesMachine mesMachineBind = new MesMachine();
        mesMachineBind.setPid(machineId);
        mesMachineBind.setModel(produce.getProduceId());
        mesMachineBind.setType(params.getBindingType());

        List<ProduceProduct> produceProductList = produceMapper.bindingFilter(mesMachineBind);

        List<String> ProductIdList = produceProductList.stream().map(it -> it.getOrderProductId()).collect(Collectors.toList());
        List<ProducePrint> producePrintList = new ArrayList<>();
        if (ProductIdList.size() > 0) {
            producePrintList = producePrintService.list(new QueryWrapper<ProducePrint>().lambda()
                    .eq(ProducePrint::getProduceId, produce.getProduceId())
                    .in(ProducePrint::getOrderProductId, ProductIdList)
                    .orderByAsc(ProducePrint::getBreed).orderByAsc(ProducePrint::getLabeling));
        }
        produce.setProduceProductList(produceProductList);
        produce.setProducePrintList(producePrintList);

        // 循环查询累计上报数量 和 最大允许上报量
        String errorMes = MesReportWork.selectMesReportTotalNum(produce, machineId, machineType, bindingType);
        if (StringUtils.isNotEmpty(errorMes)) {
            return AjaxResult.error(errorMes);
        }

        return AjaxResult.success("查询成功", produce);
    }


    @PostMapping(value = "/deleteById")
    public AjaxResult deleteById(@RequestBody Map<String, String> params) {
        String id = params.get("pid");
        produceService.removeById(id);
        // 删除前需要先修改BOM单的印刷次数减 1
        // updateBomOrderPrintNum(id, -1); // 因为提交才增加因数次数，提交之后就不能删除了，所以删除是在提交前，则不需要减 1
        // 删除细表
        produceProductService.remove(new QueryWrapper<ProduceProduct>().lambda().eq(ProduceProduct::getProduceId, id));
        producePaperService.remove(new QueryWrapper<ProducePaper>().lambda().eq(ProducePaper::getProduceId, id));
        producePrintService.remove(new QueryWrapper<ProducePrint>().lambda().eq(ProducePrint::getProduceId, id));
        producePieceService.remove(new QueryWrapper<ProducePiece>().lambda().eq(ProducePiece::getProduceId, id));
        produceCoveringService.remove(new QueryWrapper<ProduceCovering>().lambda().eq(ProduceCovering::getProduceId, id));
        mesOrderProductService.update(new UpdateWrapper<MesOrderProduct>().lambda().set(MesOrderProduct::getProduceId, null).eq(MesOrderProduct::getProduceId, id));
        return AjaxResult.success("删除成功");
    }

    // 修改BOM单的印刷次数
    public void updateBomOrderPrintNum(String pid, Integer printNum) {
        // 修改BOM单的印刷次数
        // 1.获取内文的产品信息
        List<ProduceProduct> productList = produceProductService.list(new QueryWrapper<ProduceProduct>().eq("produce_id", pid));
        // 2.保存关联的订单ID
        ArrayList<Long> longs = new ArrayList<>();
        productList.forEach(e -> {
            if (!longs.contains(Long.valueOf(e.getOrderId()))) {
                longs.add(Long.valueOf(e.getOrderId()));
            }
        });
        longs.forEach(e -> {
            // 3.修改BOM单的印刷次数
            MesOrder mesOrder = new MesOrder();
            mesOrder.setPid(e);
            mesOrder.setPrintNum(printNum);
            mesOrderMapper.updateMesOrder(mesOrder);
        });
    }

    //根据车间和版材尺寸 纸张ID获取吨位系数
    @PostMapping(value = "/getPaperTonByParams")
    public TableDataInfo getPaperTonByParams(@RequestBody Map<String, String> params) {
        MesPaperTonFactor mesPaperTonFactor = new MesPaperTonFactor();
        String paperId = params.get("paperId");
        String workshopName = params.get("workshopName");
        String sheetSize = params.get("sheetSize");

        mesPaperTonFactor.setPaperId(Long.parseLong(paperId));
        mesPaperTonFactor.setWorkshopName(workshopName);
        mesPaperTonFactor.setSheetSize(sheetSize);
        List<MesPaperTonFactor> list = produceMapper.getPaperTonByParams(mesPaperTonFactor);
        return getDataTable(list);
    }


    //查询生产进度
    @GetMapping(value = "/getschedule")
    public TableDataInfo getschedule(Produce data) {
        startPage();
        List<Produce> list = produceMapper.getschedule(data);
        if(list.size()>0){
          Produce entity = produceMapper.getscheduleSum(data);
            list.get(0).setUsePaperSum(entity.getUsePaperSum()); //用纸数量：sum(印张）*生产单订单数量/1000 保留两位小数
            list.get(0).setUrgentNumSum(entity.getUrgentNumSum()); //加急交货数量
            list.get(0).setOrderCountSum(entity.getOrderCountSum());//订单数量合计

        }
        return getDataTable(list);
    }

    //查询生产进度详情
    @GetMapping(value = "/getscheduledetail")
    public TableDataInfo getscheduledetail(String produceId, String bookCode) {
        List<ScheduleVo> nwlist = produceMapper.getschedulenw(produceId);
        List<ScheduleVo> fmlist = produceMapper.getschedulefm(produceId);
        nwlist.addAll(fmlist);
        return getDataTable(nwlist);
    }


    //查询内文生产进度详情
    @GetMapping(value = "/getNWScheduledetail")
    public TableDataInfo getNWScheduledetail(Produce produce) {
        startPage();
        List<ScheduleVo> nwlist = produceMapper.getNWSchedule(produce);
        ScheduleVo vo = produceMapper.selectSumNum(produce);
        ScheduleVo fhVo = produceMapper.selectSumNWFhDateNum(produce);
        if (nwlist != null && nwlist.size() > 0) {
            nwlist.get(0).setNotInPaperNumTotal(vo.getNotInPaperNumTotal());
            nwlist.get(0).setUsePaperNumTotal(vo.getUsePaperNumTotal());
            nwlist.get(0).setFhDateNum(fhVo.getFhDateNum());
        }
        return getDataTable(nwlist);
    }


    //生产数据统计：查询装订已排产或者印刷已排产
    @GetMapping(value = "/getPlannedBindOrPrintTasks")
    public TableDataInfo getPlannedBindOrPrintTasks(Produce produce) {
        startPage();
        List<ScheduleVo> nwlist = produceMapper.getPlannedBindOrPrintTasks(produce);
        ScheduleVo vo = produceMapper.getPlannedBindOrPrintTasksSum(produce);
        if (nwlist != null && nwlist.size() > 0) {
            nwlist.get(0).setUsePaperNumTotal(vo.getUsePaperNumTotal());
        }
        return getDataTable(nwlist);
    }



    //查询已排产装订生产单
    @GetMapping(value = "/getPlannedBindingTasks")
    public TableDataInfo getPlannedBindingTasks(Produce produce) {
        startPage();
        List<ScheduleVo> nwlist =new ArrayList<>();
        nwlist = produceMapper.getPlannedBindingTasks(produce);

        return getDataTable(nwlist);
    }

    //查询已排产印刷生产单
    @GetMapping(value = "/getPlannedPrintTasks")
    public TableDataInfo getPlannedPrintTasks(Produce produce) {
        startPage();
        List<ScheduleVo> nwlist =new ArrayList<>();
        nwlist = produceMapper.getPlannedPrintTasks(produce);

        return getDataTable(nwlist);
    }



    //问题订单
    @GetMapping(value = "/getQuestionSchedule")
    public TableDataInfo getQuestionSchedule(Produce produce) {
        startPage();
        List<ScheduleVo> nwlist = produceMapper.getQuestionNWSchedule(produce);
        ScheduleVo vo = produceMapper.selectQuestionSumNum(produce);
        ScheduleVo fhVo = produceMapper.selectQuestionSumNWFhDateNum(produce);
        if (nwlist != null && nwlist.size() > 0) {
            nwlist.get(0).setNotInPaperNumTotal(vo.getNotInPaperNumTotal());
            nwlist.get(0).setUsePaperNumTotal(vo.getUsePaperNumTotal());
            nwlist.get(0).setFhDateNum(fhVo.getFhDateNum());
        }
        return getDataTable(nwlist);
    }


    //待印刷
    @GetMapping(value = "/getWaitPrint")
    public TableDataInfo getWaitPrint(Produce produce) {
        startPage();
        List<ScheduleVo> nwlist = produceMapper.getWaitPrint(produce);
        ScheduleVo vo = produceMapper.selectWaitPrintSumNum(produce);
        if (nwlist != null && nwlist.size() > 0) {
            nwlist.get(0).setNotInPaperNumTotal(vo.getNotInPaperNumTotal());
            nwlist.get(0).setUsePaperNumTotal(vo.getUsePaperNumTotal());
        }
        return getDataTable(nwlist);
    }

    //已发货
    @GetMapping(value = "/getInvoiceList")
    public TableDataInfo getInvoiceList(Produce produce) {
        startPage();
        List<ScheduleVo> list = produceMapper.getInvoiceList(produce);
        ScheduleVo vo = produceMapper.getInvoiceListSum(produce);
        ScheduleVo lingVo = produceMapper.getInvoiceLingCountSum(produce);
        if (list != null && list.size() > 0) {
            list.get(0).setNotInPaperNumTotal(vo.getNotInPaperNumTotal());
            list.get(0).setUsePaperNumTotal(vo.getUsePaperNumTotal());
            list.get(0).setUrgentNumTotal(vo.getUrgentNumTotal());
            list.get(0).setLingCountSum(lingVo.getLingCountSum());
        }
        return getDataTable(list);
    }


    //待装订
    @GetMapping(value = "/getBinding")
    public TableDataInfo getBinding(Produce produce) {
        startPage();
        List<ScheduleVo> list = produceMapper.GetBinding(produce);
        ScheduleVo vo = produceMapper.GetBindingSum(produce);
        if (list != null && list.size() > 0) {
            list.get(0).setNotInPaperNumTotal(vo.getNotInPaperNumTotal());
            list.get(0).setUsePaperNumTotal(vo.getUsePaperNumTotal());
            list.get(0).setUrgentNumTotal(vo.getUrgentNumTotal());
        }
        return getDataTable(list);
    }


    //欠货数据统计
    @GetMapping(value = "/getShortageGoods")
    public TableDataInfo getShortageGoods(Produce produce) {
        startPage();
        List<ScheduleVo> list = produceMapper.getShortageGoods(produce);
        ScheduleVo vo = produceMapper.selectPaperSumNum(produce);
        ScheduleVo UrgentVo = produceMapper.selectUrgentSumNum(produce);
        // ScheduleVo urgentDateVo = produceMapper.getShortageGoodsUrgentDate(produce);
        if (list != null && list.size() > 0) {
            list.get(0).setNotInPaperNumTotal(vo.getNotInPaperNumTotal());
            list.get(0).setUsePaperNumTotal(vo.getUsePaperNumTotal());
            list.get(0).setUrgentNumTotal(UrgentVo.getUrgentNumTotal());
            //list.get(0).setUrgentDateList(urgentDateVo.getUrgentDateList());
        }
        return getDataTable(list);
    }

    //查询封面生产进度详情
    @GetMapping(value = "/getFMScheduleDetail")
    public TableDataInfo getFMScheduleDetail(Produce produce) {
        startPage();
        List<ScheduleVo> fmlist = produceMapper.getFMSchedule(produce);
        fmlist.forEach(e -> {
            if (StringUtils.isNotEmpty(e.getPrintAmount())) {
                e.setPrintAmount(new BigDecimal(e.getPrintAmount()).stripTrailingZeros().toPlainString());
            }
        });
        return getDataTable(fmlist);
    }


    @GetMapping(value = "/getMachineAndPieceByTechnology")
    public TableDataInfo getMachineAndPieceByTechnology(Produce produce) {
        startPage();
        List<MachinePieceByTechnologyVo> list = produceMapper.selectMachineAndPieceByTechnology(produce);
        return getDataTable(list);

    }


    //根据生产单id和机台id查询待取板贴
    @GetMapping(value = "/getTakeStay")
    public TableDataInfo getTakeStay(String produceId, String machineId) {
        Produce produce = new Produce();
        Map<String, String> params = new HashMap<>();
        params.put("produceId", produceId);
        params.put("machineId", machineId);
        produce.setParams(params);
        List<ProducePiece> list = produceMapper.getTakeStay(produce);
        return getDataTable(list);
    }


    //暂停生产单
    @PostMapping(value = "/updatesuspend")
    public AjaxResult updatesuspend(@RequestBody Map<String, String> params) {
        String pid = params.get("pid");
        String isSuspend = params.get("isSuspend");
        produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getIsSuspend, isSuspend)
                .eq(Produce::getProduceId, pid));
        return AjaxResult.success("更新成功");
    }


    //每月轮流印刷机台编辑
    @PostMapping("updateRotate")
    public AjaxResult updateRotate(@RequestBody MesRotate rotate) {
//        mesRotateService.saveOrUpdate(rotate);
        mesRotateService.update(new UpdateWrapper<MesRotate>().lambda()
                .set(MesRotate::getMachineId,rotate.getMachineId())
                .set(MesRotate::getMachineName,rotate.getMachineName())
                .eq(MesRotate::getId,rotate.getId()));
        return AjaxResult.success("更新成功");
    }

    //查询每月轮流机台
    @GetMapping("selectRotate")
    public AjaxResult selectRotate() {
        List<MesRotate> rotates = mesRotateService.list(new QueryWrapper<MesRotate>().lambda());
        return AjaxResult.success("查询成功", rotates);
    }

    @GetMapping("getMachineInventoryList")
    public TableDataInfo getMachineInventoryList(MachineInventoryVo machineInventory) {
        List<String> yearMonths = new ArrayList<>();
        if(StringUtils.isNotEmpty(machineInventory.getStartDate()) && StringUtils.isNotEmpty(machineInventory.getEndDate())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate sDate = LocalDate.parse(machineInventory.getStartDate(), formatter);
            LocalDate eDate = LocalDate.parse(machineInventory.getEndDate(), formatter);
            LocalDate startDate = LocalDate.of(sDate.getYear(), sDate.getMonthValue(), sDate.getDayOfMonth());
            LocalDate endDate = LocalDate.of(eDate.getYear(), eDate.getMonthValue(), eDate.getDayOfMonth());
            LocalDate currentDate = startDate;
            while (!currentDate.isAfter(endDate)) {
               String yearMonth = String.format("%d-%02d", currentDate.getYear(), currentDate.getMonthValue());
               yearMonths.add(yearMonth);
               currentDate = currentDate.plus(1, ChronoUnit.MONTHS);
            }
        }
        if(yearMonths.size()>0){ //盘点日期
            String inventoryMonth=String.join(",",yearMonths);
            machineInventory.setInventoryMonth(inventoryMonth);
        }

        // == 1为导出，所以不能分页
        if(machineInventory.getDataType() == null || machineInventory.getDataType() != 1){
            startPage();
        }
        // 修改查询时记得修改合计查询
        List<MachineInventoryVo> list = produceMapper.selectMachineInventoryList(machineInventory);
        if(list.size() > 0){
            // 查询合计
            BigDecimal decimal = produceMapper.selectMachineInventorySum(machineInventory);
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("realityInventory", decimal.stripTrailingZeros().toPlainString());
            list.get(0).setHashMap(hashMap);
            // 数值去零
            list.forEach(e ->{
                if(e.getUseNumber() != null) e.setUseNumber(new BigDecimal(e.getUseNumber().stripTrailingZeros().toPlainString()));
                if(e.getTkNumber() != null) e.setTkNumber(new BigDecimal(e.getTkNumber().stripTrailingZeros().toPlainString()));
                if(e.getRealityEntryInventory() != null) e.setRealityEntryInventory(new BigDecimal(e.getRealityEntryInventory().stripTrailingZeros().toPlainString()));
                if(e.getRealityOutInventory() != null) e.setRealityOutInventory(new BigDecimal(e.getRealityOutInventory().stripTrailingZeros().toPlainString()));
                if(e.getYkNumber() != null) e.setYkNumber(new BigDecimal(e.getYkNumber().stripTrailingZeros().toPlainString()));
                if(e.getRealityInventory() != null) e.setRealityInventory(new BigDecimal(e.getRealityInventory().stripTrailingZeros().toPlainString()));
                if(e.getRealityInventoryQC() != null) e.setRealityInventoryQC(new BigDecimal(e.getRealityInventoryQC().stripTrailingZeros().toPlainString()));
            });
        }
        return getDataTable(list);
    }

    @ApiOperation("导出封面生产单")
    @Log(title = "封面生产单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MachineInventoryVo machineInventory) {
        // 赋值导出标志
        machineInventory.setDataType(1);
        // 获取数据（保证数据同步，调用查询接口）
        TableDataInfo tableDataInfo = getMachineInventoryList(machineInventory);
        if(tableDataInfo.getCode() != 200){
            throw new BaseException(tableDataInfo.getMsg());
        }
        List<MachineInventoryVo> list = (List<MachineInventoryVo>) tableDataInfo.getRows();
        // 获取字典
        SysDictData dictData = new SysDictData();
        dictData.setDictType("mes_paper_specs");
        List<SysDictData> dataList = sysDictDataMapper.selectDictDataList(dictData);
        Map<String, String> map = dataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        list.forEach(e ->{
            // 前端页面显示规则，当规格为空，显示幅宽
            if(StringUtils.isNotEmpty(e.getSpecs())){
                e.setSpecs(map.get(e.getSpecs()));
            }else {
                e.setSpecs(e.getLongWide());
            }
        });
        ExcelUtil<MachineInventoryVo> util = new ExcelUtil<>(MachineInventoryVo.class);
        util.exportExcel(response, list, "机台库存查询");
    }


    //查询生产单左侧列表
    @PostMapping(value = "/GetProducelistByMachineIdAll")
    public TableDataInfo GetProducelistByMachineIdAll(@RequestBody Map<String, String> params) {
//        startPage(params);
        String produceNo = params.get("produceNo");//生产单编号
        String machineId = params.get("machineId"); //机台Id
        String status = params.get("status");
        String type = params.get("type");
        Produce produce = new Produce();
        produce.setProduceNo(produceNo);
        produce.setMachineId(machineId);
        produce.setStatus(status);
        produce.setType(type);//机台类型
        //覆膜机不筛选机台
//        if(Objects.equals(type, "7")){
//            produce.setMachineId(null);
//        }
        MesMachine mesMachine = mesMachineService.getById(machineId);
        String machineType = mesMachine.getType();
        produce.setMachineType(machineType);
        if (Objects.equals(machineType, "2")) {
            produce.setPressState("2");//印刷机
        }
        if (Objects.equals(machineType, "3")) {
            produce.setBindingState("2");//装订机
        }
        if (Objects.equals(machineType, "4")) {
            produce.setFoldState("2");//折页机
        }
        if (Objects.equals(machineType, "5") || Objects.equals(machineType, "6")) {
            produce.setTrimmingState("2");//裁切机
        }
        if (Objects.equals(machineType, "7")) {
            produce.setCoveringState("2");//覆膜机
//            produce.setMachineId(null);//不过滤机台
        }
        List<Produce> produces = produceMapper.GetProducelistByMachineIdAll(produce);

        // 返给前端的值：手动分页
        List<Produce> produceList = new ArrayList<>();
        if (params.get("pageNum") != null && params.get("pageSize") != null) {
            Integer pageNum = Integer.valueOf(params.get("pageNum"));
            Integer pageSize = Integer.valueOf(params.get("pageSize"));
            int begin = 0;
            if (pageNum.compareTo(1) > 0) {
                begin = (pageNum - 1) * pageSize;
            }
            int end = pageNum * pageSize;
            if (end > produces.size()) {
                end = produces.size();
            }

            for (int i = begin; i < end; i++) {
                produceList.add(produces.get(i));
            }
        } else {
            produceList = produces;
        }
        produceList.forEach(e -> {
            if (e.getProducePieceList() != null && e.getProducePieceList().size() > 0) {
                for (ProducePiece pieceItem : e.getProducePieceList()) {
                    ProducePrint producePrint = producePrintService.getOne(new QueryWrapper<ProducePrint>().lambda()
                            .eq(ProducePrint::getPrintId, pieceItem.getPrintId()));
                    BigDecimal lossCoefficient = StringUtils.isEmpty(producePrint.getLossCoefficient()) ? BigDecimal.ZERO : new BigDecimal(producePrint.getLossCoefficient());
                    pieceItem.setLossCoefficient(lossCoefficient);
                }
            }
            if (e.getProducePaperList() != null && e.getProducePaperList().size() > 0) {
                for (ProducePaper paper : e.getProducePaperList()) {
                    MesPaper p = mesPaperService.selectMesPaperById(Long.valueOf(paper.getPaperInfoId()));
                    paper.setPackageType(p.getPackageType());
                }

            }
            // 循环查询累计上报数量 和 最大允许上报量
            String errorMes = MesReportWork.selectMesReportTotalNum(e, machineId, machineType, "");
            if (StringUtils.isNotEmpty(errorMes)) {
                throw new BaseException(errorMes);
            }
        });

        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setRows(produceList);
        tableDataInfo.setTotal(produces.size());
        return tableDataInfo;
    }

    // 修改印数信息
    @PostMapping("/upProducePrint")
    @Transactional
    public AjaxResult upProducePrint(@RequestBody List<ProducePrint> printList) {
        // 获取主表信息
        List<Produce> produceList = produceService.list(new QueryWrapper<Produce>().eq("produce_id", printList.get(0).getProduceId()));
        Produce produce = produceList.get(0);
        // 修改印刷：品牌、纸型。定量、幅宽、纸张编码
        ArrayList<String> paperNoList = new ArrayList<>(); // 保存纸张编码
        ArrayList<MesPaper> paperList = new ArrayList<>();// 保存纸张信息
        printList.forEach(e -> {
            // 修改印刷信息
            producePrintService.update(new UpdateWrapper<ProducePrint>()
                    .set("brand", e.getBrand()) // 品牌
                    .set("paper_type", e.getPaperType()) // 纸型
                    .set("weight", e.getWeight()) // 定量/克重
                    .set("cloth_width", e.getClothWidth()) // 幅宽
                    .set("paper_no", e.getPaperNo()) // 纸张编码
                    .eq("print_id", e.getPrintId())
            );
            // 修改产品：status == null，修改产品的纸张编码、纸型、纸张名称
            // 查询修改印刷后的纸张信息
            MesPaper mesPaper = new MesPaper();
            mesPaper.setCode(e.getPaperNo());
            List<MesPaper> mesPapers = mesPaperService.selectMesPaperList(mesPaper);
            if (StringUtils.isEmpty(e.getStatus())) {
                produceProductService.update(new UpdateWrapper<ProduceProduct>()
                        .set("paper_no", e.getPaperNo()) // 纸张编码
                        .set("paper_name", mesPapers.get(0).getName()) // 纸张名称
                        .set("paper_type", e.getPaperType()) // 纸型
                        .eq("order_product_id", e.getOrderProductId())
                );
            }
            // 保存纸张信息
            if (!paperNoList.contains(e.getPaperNo())) {
                paperNoList.add(e.getPaperNo());
                mesPapers.forEach(x -> {
                    x.setOrderProductId(e.getOrderProductId());
                });
                paperList.addAll(mesPapers);
            }
        });
        // 根据纸张编码分组
        Map<String, List<ProducePrint>> listMap = printList.stream().collect(Collectors.groupingBy(ProducePrint::getPaperNo));
        // 平张：合计用纸总令数；卷筒：合计轮转吨数
        HashMap<String, BigDecimal> hashMap = new HashMap<>();
        for (String s : listMap.keySet()) {
            BigDecimal reamAmount = new BigDecimal(0);
            List<ProducePrint> producePrints = listMap.get(s);
            for (ProducePrint print : producePrints) {
                // 印刷方式 1平张，2轮转
                if ("1".equals(print.getPrintType())) {
                    BigDecimal decimal = StringUtils.isEmpty(print.getTotalReamAmount()) ? new BigDecimal(0) : new BigDecimal(print.getTotalReamAmount());
                    BigDecimal decimal1 = StringUtils.isEmpty(print.getLxjf()) ? new BigDecimal(0) : new BigDecimal(print.getLxjf());
                    reamAmount = reamAmount.add(decimal).add(decimal1);
                } else {
                    BigDecimal decimal = Double.isNaN(print.getRotateTon()) ? new BigDecimal(0) : BigDecimal.valueOf(print.getRotateTon());
                    BigDecimal decimal1 = StringUtils.isEmpty(print.getLxjf()) ? new BigDecimal(0) : new BigDecimal(print.getLxjf());
                    reamAmount = reamAmount.add(decimal).add(decimal1);
                }
            }
            hashMap.put(s, reamAmount);
        }

        // 处理纸张信息
        ArrayList<ProducePaper> paperArrayList = new ArrayList<>();
        int xh = 0;
        for (MesPaper paper : paperList) {
            // 获取纸张数量
            double reamAmount = hashMap.get(paper.getCode()) == null ? 0.0 : Double.valueOf(hashMap.get(paper.getCode()).toPlainString());
            ProducePaper producePaper = new ProducePaper();
            producePaper.setPaperInfoId(String.valueOf(paper.getId()));
            producePaper.setOrderProductId(paper.getOrderProductId());
            producePaper.setType(paper.getMaterial());
            producePaper.setPaperName(paper.getName());
            producePaper.setPaperType(paper.getPaperType());
            producePaper.setWeight(paper.getWeight() == null ? 0.0 : Double.parseDouble(paper.getWeight().toPlainString()));
            producePaper.setSpecifications(paper.getSpecs() == null ? null : paper.getSpecs().toString());
            producePaper.setLength(paper.getLongWide() == null ? 0.0 : Double.parseDouble(paper.getLongWide().toPlainString()));
            producePaper.setUnit(paper.getUnit());
            producePaper.setAmount(paper.getQuantity() == null ? 0.0 : Double.parseDouble(paper.getQuantity().toPlainString()));
            producePaper.setReamAmount(reamAmount);
            producePaper.setBrand(paper.getBrand());
            producePaper.setSize(null);
            producePaper.setPaperNo(paper.getCode());
            //序列号
            String xlh = PinYinUtils.sequence(xh);
            producePaper.setProduceId(printList.get(0).getProduceId());
            producePaper.setPaperProduceNo(produce.getProduceNo() + "ZZ" + xlh);
            producePaper.setCreateBy(SecurityUtils.getUsername());
            producePaper.setCreateTime(DateUtils.getNowDate());
            xh = xh + 1;
            paperArrayList.add(producePaper);
        }
        // 根据印刷管理，更新纸张信息：删除历史新增新的
        producePaperService.remove(new QueryWrapper<ProducePaper>().eq("produce_id", printList.get(0).getProduceId()));
        producePaperService.saveBatch(paperArrayList);
        return AjaxResult.success();
    }

    @PostMapping(value = "/tempSubmit")
    @Transactional
    public AjaxResult tempSubmit(@RequestBody Produce produce) {
        if (StringUtils.isNotEmpty(produce.getProductId())) {
            produceProductService.update(new UpdateWrapper<ProduceProduct>()
                    .set("temp_status", 1) // 状态
                    .eq("product_id", produce.getProductId()));
        }
        return AjaxResult.success();
    }

    // 修改产品信息 -- 修改关联的封面生产单信息
    @PostMapping("/upProduceProduct")
    @Transactional
    public AjaxResult upProduceProduct(@RequestBody List<ProduceProduct> productList) {
        boolean isJoinFm = false; // 是否关联封面生产单
        for (ProduceProduct e : productList) {
            produceProductService.update(new UpdateWrapper<ProduceProduct>()
                    .set("produce_ids", e.getProduceIds())
                    .set("produce_nos", e.getProduceNos())
                    .set("system_out_fm", e.getSystemOutFm())
                    .eq("product_id", e.getProductId())
            );
            // 有值证明关联封面生产单
            if (StringUtils.isNotEmpty(e.getProduceIds())) {
                isJoinFm = true;
            }
        }
        if (isJoinFm) {
            // 修改对应的主表
            produceService.update(new UpdateWrapper<Produce>().set("is_join_fm", "1").eq("produce_id", productList.get(0).getProduceId()));
        } else {
            // 修改对应的主表
            produceService.update(new UpdateWrapper<Produce>().set("is_join_fm", "0").eq("produce_id", productList.get(0).getProduceId()));
        }
        return AjaxResult.success();
    }

    // 选择封面生产单
    @PostMapping(value = "/listFm")
    public TableDataInfo listFm(@RequestBody Map<String, String> params) {
        Produce produce = new Produce();
        produce.setParams(params);
        startPage(params);
        List<Produce> produces = produceMapper.getListFM2(produce);
        for (Produce produce1 : produces) {
            if (StringUtils.isNotEmpty(produce1.getProduceCount())) {
                produce1.setProduceCount(new BigDecimal(produce1.getProduceCount()).stripTrailingZeros().toPlainString());
            }
            if (StringUtils.isNotEmpty(produce1.getProduceCountYu())) {
                produce1.setProduceCountYu(new BigDecimal(produce1.getProduceCountYu()).stripTrailingZeros().toPlainString());
            }
        }
        return getDataTable(produces);
    }

    // 修改包内数量
    @PostMapping("/upPackInNum")
    public AjaxResult upPackInNum(@RequestBody Produce produce){
        if(StringUtils.isEmpty(produce.getProduceId())){
            return AjaxResult.error("主键不能为空");
        }
        produceService.update(new UpdateWrapper<Produce>()
                .set("pack_in_num", produce.getPackInNum())
                .eq("produce_id", produce.getProduceId()));
        return AjaxResult.success();
    }


    //生产单一键撤回
    @PostMapping("/withdraw")
    public AjaxResult withdraw(@RequestBody Map<String, String> params){
        String produceId = params.get("produceId");//生产单id
        List<ReportWork> reportWorks= reportWorkService.list(new QueryWrapper<ReportWork>()
                .lambda().eq(ReportWork::getProduceId,produceId));
        if(reportWorks!=null&&reportWorks.size()>0){
            return AjaxResult.error("已印刷报工不能撤回");
        }else{
            produceMapper.Withdrawupdate(produceId);
            produceMapper.Withdrawdelete(produceId);
            return AjaxResult.success();
        }
    }
}

